<?php
namespace core\service;
// +----------------------------------------------------------------------
// | 基础服务
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2017 Even Yin All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Even yin <416467069@qq.com> <13022156261>
// +----------------------------------------------------------------------
use think\Session as Session;         
use think\Cache   as Cache;           
use think\Request as Request;
use think\Db as Db;
use core\extend\Sms                 as Sms;
use core\extend\Wechat              as Wechat;
class BaseService
{
  protected $ip;                  //客户端ip
  protected $client;              //客户端类型 pc、wap、wechat
  protected $request_type;        //请求类型
  protected $module;
  protected $controller;
  protected $action;
  protected $system;
  protected $model;
  protected $error;
  /* ------------------------------------------------------------------ */
  /*
  * 构造函数
  */
  public function __construct(){
    $this->_init();
  }
  /* ------------------------------------------------------------------ */
  /*
  * 初始函数
  */
  function _init(){
    $this->getSystem();
    $this->getClient();
    $this->getRequestType();
    $this->getIp();
    $this->getAction();
    $this->getController();
    $this->getModule();
  }
  /* ------------------------------------------------------------------ */
  /*
  * 获取系统信息
  */
  function getSystem(){
    $this->system = Cache::get('system');
    if(empty($this->system)){
      $this->system = $this->model('System')->getInfo(['id'=>1]);
      if(empty($this->system)){
        if($this->model('System')->add(['id'=>1])){
          $this->system = $this->model('System')->getInfo(['id'=>1]);
        }
      }
      Cache::set('system',$this->system,3600);
    }
    return $this->system;
  }
  /* ------------------------------------------------------------------ */
  /*
  * 获取客户端类型
  */
  function getClient(){
    $this->client = 'pc';
    if(Request::instance()->isMobile()) $this->client = 'mobile';
		if(preg_match('/micromessenger/i',Request::instance()->header('user-agent'))) $this->client = 'wechat';
    return $this->client;
  }
  /* ------------------------------------------------------------------ */
  /*
  * 获取客户端请求类型
  */
  function getRequestType(){
    if(Request::instance()->isAjax()){$this->request_type   = 'ajax';}
    if(Request::instance()->isGet()){$this->request_type    = 'get';}
    if(Request::instance()->isPost()){$this->request_type   = 'post';}
    if(Request::instance()->isPut()){$this->request_type    = 'put';}
    if(Request::instance()->isDelete()){$this->request_type = 'delete';}
    return $this->request_type;
  }
  /* ------------------------------------------------------------------ */
  /*
  * 获取客户端IP
  */
  function getIp(){
    $this->ip = Request::instance()->ip();
    return $this->ip;
  }
  /* ------------------------------------------------------------------ */
  /*
  * 获取操作方法名
  */
  function getAction(){
    $this->action = strtolower(Request::instance()->action());
    return $this->action;
  }
  /* ------------------------------------------------------------------ */
  /*
  * 获取控制器名
  */
  function getController(){
    $this->controller = strtolower(Request::instance()->controller());
    return $this->controller;
  }
  /* ------------------------------------------------------------------ */
  /*
  * 获取模块名
  */
  function getModule(){
    $this->module = strtolower(Request::instance()->module());
    return $this->module;
  }
  /* -----------------------------------END------------------------------- */
  /*
  * 获取菜单
  */
  function getMenu($rules=[]){
    $menu = [];
    foreach ($rules as $v) {
      if($v['is_menu']==1){
        $menu[] = $v;
      }
    }
    return $menu;
  }
  /* -----------------------------------END------------------------------- */
  /*
  * 验证权限
  */
  function checkAuth($module='',$controller='',$action='',$auth=[]){
    $module = empty($module)?$this->module:$module;
    $controller = empty($controller)?$this->controller:$controller;
    $action = empty($action)?$this->action:$action;
    foreach ($auth as $v) {
      if(strtolower($module) == strtolower($v['module']) && strtolower($controller) == strtolower($v['controller']) && strtolower($action) == strtolower($v['action'])){
        return true;
      }
    }
    return false;
  }
  /* ------------------------------------------------------------------ */
  /*
  * 获取随机字符串
  */
  function getRandomStr($length=8){
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
		$str = '';
		for($i=0;$i<$length;$i++){
			$str .= $chars[ mt_rand(0, strlen($chars) - 1) ];
		}
		return $str;
  }
  /* ------------------------------------------------------------------ */
  /*
  * 获取随机数字码
  */
  function getRandomNum($length=6){
    $chars = '0123456789';
		$str = '';
		for($i=0;$i<$length;$i++){
			$str .= $chars[ mt_rand(0, strlen($chars) - 1) ];
		}
		return $str;
  }
  /* ------------------------------------------------------------------ */
  /*
  * 加载微信SDK
  */
  function loadWechat($type=''){
    $wechat = new Wechat(Request::instance()->param('token'));
    return $wechat->load($type);
  }
  /* ------------------------------------------------------------------ */
  /*
  * 发送客服消息
  */
  function sendWechatMessage($token='',$data=[]){
    $wechatService = new Wechat($token);
    $wechat = $wechatService->load('Receive');
    if($wechat->sendCustomMessage($data)){
      return true;
    }
    $this->error = $wechat->errMsg;
    return false;
  }
  /* ------------------------------------------------------------------ */
  /*
  * 发送客服文字消息
  */
  function sendWechatMessageText($token,$openid,$text){
    if(empty($token)){$this->error = 'token不存在！';return false;}
    if(empty($openid)){$this->error = 'openid不存在！';return false;}
    if(empty($text)){$this->error = 'text不存在！';return false;}
    $data = [
      'touser' => $openid,
      'msgtype' => 'text',
      'text' => ['content'=>$text]
    ];
    return $this->sendWechatMessage($token,$data);
  }
  /* ------------------------------------------------------------------ */
  /*
  * 发送客服图片消息
  */
  function sendWechatMessageImage($token,$openid,$media_id){
    if(empty($token)){$this->error = 'token不存在！';return false;}
    if(empty($openid)){$this->error = 'openid不存在！';return false;}
    if(empty($media_id)){$this->error = 'media_id不存在！';return false;}
    $data = [
      'touser' => $openid,
      'msgtype' => 'image',
      'image' => ['media_id'=>$media_id]
    ];
    return $this->sendWechatMessage($token,$data);
  }
  /* ------------------------------------------------------------------ */
  /*
  * 发送客服语音消息
  */
  function sendWechatMessageVoice($token,$openid,$media_id){
    if(empty($token)){$this->error = 'token不存在！';return false;}
    if(empty($openid)){$this->error = 'openid不存在！';return false;}
    if(empty($media_id)){$this->error = 'media_id不存在！';return false;}
    $data = [
      'touser' => $openid,
      'msgtype' => 'voice',
      'voice' => ['media_id'=>$media_id]
    ];
    return $this->sendWechatMessage($token,$data);
  }
  /* ------------------------------------------------------------------ */
  /*
  * 发送客服视频消息
  */
  function sendWechatMessageVideo($token,$openid,$title,$description,$thumb_media_id,$media_id){
    if(empty($token)){$this->error = 'token不存在！';return false;}
    if(empty($openid)){$this->error = 'openid不存在！';return false;}
    if(empty($title)){$this->error = 'title不存在！';return false;}
    if(empty($description)){$this->error = 'description不存在！';return false;}
    if(empty($thumb_media_id)){$this->error = 'thumb_media_id不存在！';return false;}
    if(empty($media_id)){$this->error = 'media_id不存在！';return false;}
    $data = [
      'touser' => $openid,
      'msgtype' => 'video',
      'video' => ['media_id'=>$media_id,'thumb_media_id'=>$thumb_media_id,'title'=>$title,'description'=>$description]
    ];
    return $this->sendWechatMessage($token,$data);
  }
  /* ------------------------------------------------------------------ */
  /*
  * 发送客服公众号图文消息
  */
  function sendWechatMessageMpnews($token,$openid,$media_id){
    if(empty($token)){$this->error = 'token不存在！';return false;}
    if(empty($openid)){$this->error = 'openid不存在！';return false;}
    if(empty($media_id)){$this->error = 'media_id不存在！';return false;}
    $data = [
      'touser' => $openid,
      'msgtype' => 'mpnews',
      'mpnews' => ['media_id'=>$media_id]
    ];
    return $this->sendWechatMessage($token,$data);
  }
  /* ------------------------------------------------------------------ */
  /*
  * 发送客服图文消息
  */
  function sendWechatMessageNews($token,$openid,$articles=[]){
    if(empty($token)){$this->error = 'token不存在！';return false;}
    if(empty($openid)){$this->error = 'openid不存在！';return false;}
    if(empty($articles)){$this->error = '文章数组(包含字段：title，description，url，picurl)不存在！';return false;}
    $data = [
      'touser' => $openid,
      'msgtype' => 'news',
      'news' => ['articles'=>$articles]
    ];
    return $this->sendWechatMessage($token,$data);
  }
  /* ------------------------------------------------------------------ */
  /*
  * 验证手机号
  */
  function checkMobileCode($mobile='',$code=''){
    if(empty($mobile) || empty($code) || $code!=Session::get('MOBILE_CODE_'.$mobile)){
      $this->error = 'mobile or code is error!';
      return false;
    }
    return true;
  }
  /* ------------------------------------------------------------------ */
  /*
  * 获取手机验证码
  */
  function sendMobileCode($mobile='',$type='default',$param=[]){
    $sms = new Sms($mobile);
    if($sms->send()){
      Session::set('MOBILE_CODE_'.$mobile,$sms->getCode());
      return true;
    }
    $this->error = $sms->getError();
    return false;
  }
  /* ------------------------------------------------------------------ */
  /*
  * 数据库事务开启
  */
  public function startTrans(){
      Db::startTrans();
  }
  /* ------------------------------------------------------------------ */
  /*
  * 数据库事务提交
  */
  public function commit(){
      Db::commit();
  }
  /* ------------------------------------------------------------------ */
  /*
  * 数据库事务回滚
  */
  public function rollback(){
      Db::rollback();
  }
  /* ------------------------------------------------------------------ */
  /*
  * 设置模型
  */
  function model($model=''){
    if(is_file(ROOT_PATH.'core/model/'.$model.'.php')){
      $model = '\\core\\model\\'.$model;
      $this->model = new $model();
      return $this;
    }
    $this->error = '模型不存在！';
    return $this;
  }
  /* ------------------------------------------------------------------ */
  /*
  * 数据验证
  */
  function validate($data=[],$scene='',$batch = NULL){
    if($this->model->validateData($data,$scene,$batch)) return true;
    $this->error = $this->model->getError();
    return false;
  }
  /* ------------------------------------------------------------------ */
  /*
  * 获取分页列表
  */
  function getPageList($page=1,$page_size=20,$condition=[],$order='',$field=''){
    return $this->model->pageQuery($page,$page_size,$condition,$order,$field);
  }
  /* ------------------------------------------------------------------ */
  /*
  * 获取分页列表
  */
  function getList($condition=[],$order='',$field=''){
    return $this->model->getQueryData($condition,$order,$field);
  }
  /* ------------------------------------------------------------------ */
  /*
  * 获取详情
  */
  function getInfo($condition=[],$field=''){
    return $this->model->getInfo($condition,$field);
  }
  /* ------------------------------------------------------------------ */
  /*
  * 添加
  */
  function add($data=[],$scene=''){
    if(empty($data)){$this->error = '数据为空！';return false;}
    if($this->model->save($data,[],$scene)) return true;
    $this->error =$this->model->getError(); //'添加失败！';
    return false;
  }
  /* ------------------------------------------------------------------ */
  /*
  * 修改
  */
  function edit($data=[],$condition=[],$scene=''){
    if(empty($condition)){$this->error = '查询条件为空！'; return false;}
    if($this->model->save($data,$condition,$scene)) return true;
    $this->error = $this->model->getError();//'修改失败！';
    return false;
  }
  /* ------------------------------------------------------------------ */
  /*
  * 修改字段
  */
  function editField($pk_name='',$pk_value='',$field_name='',$field_value=''){
    if($pk_name==='' || $pk_value==='' || $field_name===''){$this->error = '参数错误！'; return false;}
    if($this->model->modifyTableField($pk_name,$pk_value,$field_name,$field_value)) return true;
    $this->error = '修改失败！';
    return false;
  }
  /* ------------------------------------------------------------------ */
  /*
  * 删除
  */
  function delete($id=''){
    if($this->model->destroy($id)) return true;
    $this->error = '删除失败！';
    return false;
  }
  /* ------------------------------------------------------------------ */
  /*
  * 条件删除
  */
  function deleteByCondition($condition=[]){
    if($this->model->where($condition)->delete()) return true;
    $this->error = '删除失败！';
    return false;
  }
  /* ------------------------------------------------------------------ */
  /*
  * 获取总数
  */
  function getCount($condition=[]){
    return $this->model->getCount($condition);
  }
  /* ------------------------------------------------------------------ */
  /*
  * 获取总合
  */
  function getSum($condition,$field){
    return $this->model->getSum($condition,$field);
  }
  /* ------------------------------------------------------------------ */
  /*
  * 获取最大值
  */
  function getMax($condition,$field){
    return $this->model->getMax($condition,$field);
  }
  /* ------------------------------------------------------------------ */
  /*
  * 获取最小值
  */
  function getMin($condition,$field){
    return $this->model->getMin($condition,$field);
  }
  /* ------------------------------------------------------------------ */
  /*
  * 获取均值
  */
  function getAvg($condition,$field){
    return $this->model->getAvg($condition,$field);
  }
  /* ------------------------------------------------------------------ */
  /*
  * 写入日志
  */
  public function recordLog($uid,$is_success,$remark){
    $data = [];
    $data['uid'] = $uid;
    $data['module'] = $this->module;
    $data['controller'] = $this->controller;
    $data['action'] = $this->action;
    $data['method'] = $this->request_type;
    $data['params'] = json_encode(Request::instance()->param(),true);
    $data['is_success'] = $is_success;
    $data['remark'] = $remark;
    $data['create_time'] = strtotime(date('YmdHis'));
    $log = new UserActionLogModel();
    if($log->save($data)){
      return true;
    }
    return false;
  }
  /* ------------------------------------------------------------------ */
  /*
  * 获取错误信息
  */
  public function getError(){
    return $this->error;
  }
  /* ------------------------------------------------------------------ */
}
